<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    style="top: 50px"
    cancelText="关闭"
  >
    <a-card :bordered="false">
      <a-row :gutter="8">
        <a-col :span="6">
          <div>
            <a-input-search v-model="searchValue" style="margin-bottom: 8px" placeholder="Search" />
            <a-tree  ref="categoryTree" :auto-expand-parent="true" :tree-data="gData" :replaceFields="replaceFields" @select="onSelect">
              <template #title="{ name }">
                <!--                <span>{{name}}</span>-->
                <span v-if="name.indexOf(searchValue) > -1">
                  {{ name.substr(0, title.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{ name.substr(title.indexOf(searchValue) + searchValue.length) }}
                </span>
                <span v-else>{{ name }}</span>
              </template>
            </a-tree>
          </div>
        </a-col>
        <a-col :span="18">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item label="编号">
                    <a-input placeholder="请输入编号" v-model="queryParam.code"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item label="名称">
                    <a-input placeholder="请输入名称" v-model="queryParam.name"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item label="规格">
                    <a-input placeholder="请输入规格" v-model="queryParam.noneSpec"></a-input>
                  </a-form-item>
                </a-col>
                <template v-if="toggleSearchStatus">
                  <a-col :xl="6" :lg="7" :md="8" :sm="24">
                    <a-form-item label="状态">
                      <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="erp_status" />
                    </a-form-item>
                  </a-col>
                </template>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                    <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                    <a @click="handleToggleSearch" style="margin-left: 8px">
                      {{ toggleSearchStatus ? '收起' : '展开' }}
                      <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                    </a>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 查询区域-END -->
          <!-- table区域-begin -->
          <div>
            <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
              <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
              <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
              >项
              <a style="margin-left: 24px" @click="onClearSelected">清空</a>
            </div>

            <a-table
              ref="table"
              size="middle"
              :scroll="{ x: true }"
              bordered
              :rowKey="
                (record, index) => {
                  return record.id
                }
              "
              :columns="columns"
              :dataSource="dataSource"
              :pagination="ipagination"
              :loading="loading"
              :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: checkval }"
              class="j-table-force-nowrap1"
              @change="handleTableChange"
            />
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="8">
        <a-col :span="24">
          <a-table
            ref="table1"
            size="middle"
            :scroll="{ x: true }"
            bordered
            :rowKey="
              (record, index) => {
                return record.id
              }
            "
            :columns="columns"
            :dataSource="selectionRowsAll"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: checkval ,preserveSelectedRowKeys: true }"
            class="j-table-force-nowrap1"
          />
        </a-col>
      </a-row>
    </a-card>
  </j-modal>
</template>
<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@api/manage'

export default {
  name: 'ErpCategoryGoodsListModel',
  mixins: [JeecgListMixin, mixinDevice],
  components: {},
  // props: ['category', "modalWidth",],
  props: {
    category: {
      type: Number,
      required: false,
    },
    modalWidth: {
      type: Number,
      required: false,
      default: 1250,
    },
    checkval: {
      type: String,
      default: 'radio',
    },
    supplierId: {
      type: String,
      required: false,
    },
  },
  data() {
    return {
      selectedRowsObj: {},
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      gData: [{ key: '1', title: '1', children: [{ key: '1-1', title: '1-1' }] }],
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'code',
      },
      searchValue: '',
      description: '物料基础信息管理页面',
      visible: false,
      title: '选择物料',
      disableMixinCreated: true,
      queryParam: { categoryCode: this.category },
      categoryCode: '',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '编号',
          align: 'center',
          dataIndex: 'code',
        },
        {
          title: '名称',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'noneSpec',
        },
        {
          title: '包装规格(g)',
          align: 'center',
          dataIndex: 'packSpec',
        },
        {
          title: '物料种类',
          align: 'center',
          dataIndex: 'categoryCodeText',
        },
        {
          title: '客户物料编号',
          align: 'center',
          dataIndex: 'customCode',
        },
        {
          title: '计量单位',
          align: 'center',
          dataIndex: 'meUnit_dictText',
        },
        {
          title: '辅助单位',
          align: 'center',
          dataIndex: 'auUnit_dictText',
        },
        // {
        //   title: '供应商',
        //   align: "center",
        //   dataIndex: 'supplierName'
        // },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText',
        },
        {
          title: '换算率',
          align: 'center',
          dataIndex: 'coRate',
        },
        {
          title: '物料分类',
          align: 'center',
          dataIndex: 'classificationId_dictText',
        },
        // {
        //   title: '是否有版样',
        //   align: 'center',
        //   dataIndex: 'isPattern_dictText',
        // },
        {
          title: '安全库存',
          align: 'center',
          dataIndex: 'stockQuantity',
        },
        {
          title: '所属仓库',
          align: 'center',
          dataIndex: 'warehouseCodeText',
        },
        {
          title: '是否关联包材',
          align: 'center',
          dataIndex: 'isAssBc_dictText',
        },
        {
          title: '是否公用',
          align: 'center',
          dataIndex: 'isPublic_dictText',
        },
        {
          title: '是否领料',
          align: 'center',
          dataIndex: 'isUse_dictText',
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
        },
      ],
      url: {
        list: '/pattern/crmPatternManagement/ReviewPackageList',
        delete: '/base/erpGoods/delete',
        deleteBatch: '/base/erpGoods/deleteBatch',
        exportXlsUrl: '/base/erpGoods/exportXls',
        importExcelUrl: 'base/erpGoods/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    selectionRowsAll() {
      return Object.values(this.selectedRowsObj); // 2. 实时计算
    }
  },
  watch: {
    category(newval, oldval) {
      this.loadGoodsCategory()
    },
  },
  mounted() {
    this.loadGoodsCategory()
  },
  methods: {
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      // 3. 先删取消的
      Object.keys(this.selectedRowsObj)
        .filter(k => !selectedRowKeys.includes(k))
        .forEach(k => this.$delete(this.selectedRowsObj, k));
      // 4. 再写/更新新的
      selectionRows.forEach(r => this.$set(this.selectedRowsObj, r.id, r));
      console.log('Map 内容：', ...this.selectedRowsObj)
      console.log(this.selectedRowKeys,this.selectionRowsAll)
    },
    loadGoodsCategory() {
      getAction('/goods/erpGoodsCategory/categorylist', { category: this.category })
        .then(res => {
          if (res.success && res.result.length) {
            this.gData = res.result;
            console.log("aaaaaaaaaaaaaaaaaaaaaa1")
            // 1. 取首节点
            const first = res.result[0];
            const key = first.code;          // 你的 key 字段
            console.log("aaaaaaaaaaaaaaaaaaaaaa12")

            // 2. 等树渲染完再操作
            this.$nextTick(() => {
              // 3. 立即带条件查表
              this.categoryCode = key;
              this.queryParam.categoryCode = key;
              this.loadData(1);
            });
          }
        });
    },
    onSelect(selectedKeys, e) {
      console.log('选择的值', selectedKeys, e)
      this.categoryCode = selectedKeys
      this.queryParam = { categoryCode: selectedKeys }
      this.loadData()
    },
    handleSubmit() {
      this.getGoodsSelectRows()
      // this.searchReset(false)
      this.queryParam = {}
      this.onClearSelected()
      this.close()
    },
    add() {
      this.showModal()
    },
    showModal() {
      this.dataSource = []
      this.visible = true

      // this.loadData();
    },
    getGoodsSelectRows() {
      let selectedRow = null
      let selectedRowKey=null
      if (this.checkval == 'radio') {
        selectedRow = this.selectionRows[0]
        selectedRowKey=this.selectedRowKey[0]
      } else {
        selectedRow = this.selectionRows
        selectedRowKey=this.selectedRowKeys
      }
      // if(this.checkval=='radio'){
      //    selectedRow = this.selectionRows[0];
      // }else{
      //    selectedRow = this.selectionRows
      // }
      //传递选中的数据
      this.$emit('goodsOk', selectedRowKey)
      this.$emit('packageOk', selectedRow)
      this.$emit('goodRowsOk',selectedRow)
    },
    initDictConfig() {},
    close() {
      this.queryParam = {}
      this.selectedRowKeys = []
      this.selectionRows = []
      this.visible = false
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'code', text: '编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'name', text: '名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'noneSpec', text: '规格', dictCode: '' })
      fieldList.push({ type: 'int', value: 'packSpec', text: '包装规格(g)', dictCode: '' })
      fieldList.push({ type: 'sel_user', value: 'categoryCode', text: '物料种类' })
      fieldList.push({ type: 'string', value: 'customCode', text: '客户物料编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'meUnit', text: '计量单位', dictCode: 'ji_unit' })
      fieldList.push({ type: 'string', value: 'auUnit', text: '辅助单位', dictCode: 'zl_unit' })
      fieldList.push({ type: 'int', value: 'status', text: '状态', dictCode: 'erp_status' })
      fieldList.push({ type: 'string', value: 'coRate', text: '换算率', dictCode: '' })
      fieldList.push({
        type: 'string',
        value: 'classificationId',
        text: '物料分类',
        dictCode: 'erp_goods_classification,name,id',
      })
      fieldList.push({ type: 'int', value: 'isPattern', text: '是否有版样', dictCode: 'is_open' })
      fieldList.push({ type: 'int', value: 'stockQuantity', text: '安全库量', dictCode: '' })
      fieldList.push({ type: 'sel_user', value: 'warehouseCode', text: '所属仓库' })
      fieldList.push({ type: 'int', value: 'isAssBc', text: '是否关联包材', dictCode: 'is_open' })
      fieldList.push({ type: 'int', value: 'isPublic', text: '是否公用', dictCode: 'is_open' })
      fieldList.push({ type: 'string', value: 'isUse', text: '是否领料', dictCode: 'is_open' })
      fieldList.push({ type: 'string', value: 'remark', text: '备注', dictCode: '' })
      this.superFieldList = fieldList
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      // if(this.supplierId){
      //   params.supplierId = this.supplierId;
      // }
      if (this.categoryCode) {
        params.categoryCode = this.categoryCode
      }

      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
